package com.shuyu.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuyu.common.core.domain.entity.Customer;
import com.shuyu.common.core.domain.model.LoginUser;
import com.shuyu.common.exception.ServiceException;
import com.shuyu.common.utils.MessageUtils;
import com.shuyu.common.utils.StringUtils;
import com.shuyu.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Component("CustomerDetailsServiceImpl")
public class CustomerDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(CustomerDetailsServiceImpl.class);

    @Resource
    private CustomerService customerService;
    
    @Resource
    private SysPasswordService passwordService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        Customer user = customerService.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getUsername, username).last("limit 1"));
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(Customer customer)
    {
        return new LoginUser(customer.getId(), customer);
    }
}
